﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LEET.CommonInterfaces.Models;
using Tedds_Tool.Instructions;
using LEET.Utilities;

namespace LEET.LEETCommon.Model
{
    public abstract class Instruction : IInstruction
    {
        protected String [] args;
        public String Name { get; protected set; }
        public String InstructionType { get; protected set; }

        public Instruction(String [] str)
        {
            Name = "";
            InstructionType = "";
            args = str;
        }

        public override String ToString()
        {
            return String.Join<String>(" | ", args);
        }

        public static String[] ParseInstruction(String str)
        {
            List<String> ret = new List<String>();
            bool inQuote = false;
            int start = 0;
            int length = 0;

            while (start < str.Length)
            {
                if (start + length >= str.Length)
                {
                    ret.Add(str.Substring(start).Trim());
                    start = str.Length;
                } 
                else if (!inQuote && str[start + length] == '|')
                {
                    ret.Add(str.Substring(start, length).Trim());
                    start += length + 1;
                    length = 0;
                }
                else if (str[start + length] == '"')
                {
                    inQuote = !inQuote;
                    length++;
                }
                else
                {
                    length++;
                }
            }
            
            return ret.ToArray();
        }

        protected void AddErrorMsg(String msg)
        {
            errors.Add(msg);
        }

        public virtual bool Valid { get { return Errors.Count <= 0; } }

        private IList<String> errors = new List<String>();
        public virtual IList<String> Errors { get { return errors; } }

        public abstract String PlainText();

        public override bool Equals(Object obj)
        {
            if(obj == null || !(obj is Instruction) )
            {
                return false;
            }
            Instruction other = (Instruction)obj;
            return args.Equals(other.args);
        }

        public override int GetHashCode()
        {
            return args.GetHashCode();
        }

        public abstract string RenderStaticCall();
    }
}
